package com.sky.utils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.UnknownHostException;

/**
 * @author 冰白寒祭
 * @date 2023-08-31 20:48:54
 * @description 上传文件到本地目录
 */

@Slf4j
@Data
public class UploadToLocal {

    private String serverPort;
    private String savePath;

    /**
     * @MethodName: upload
     * @Author 冰白寒祭
     * @Description: 上传文件到本地目录
     * @Date: 2023/8/31 0031 20:51
     * @param: MultipartFile
     * @param: objectName   构建新文件名称
     * @return: 文件请求路径
     */
    public String uploadLocal(MultipartFile file, String objectName) throws IOException {

//        Map<String, Object> result = new HashMap<>();
        String filePath;
        if (file.isEmpty()) {
            return null;
        } else {
            // 创建文件路径
            File fileDir = new File(savePath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            // 新文件路径+新文件名
            filePath = fileDir + "/" + objectName;
            // 保存文件
            file.transferTo(new File(filePath));
        }
        String hostAddress;
        try {
            hostAddress = Inet4Address.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        String url = "http://" + hostAddress + ":" + serverPort + "/image/";
        return url + objectName;
    }
}
